package umg.os.devices;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.InputMismatchException;

public class DataManipulationUtilities {

	private DataManipulationUtilities() {

	}

	/**
	 * Gets the 3 lest significant bytes from <b>intToCast</b>.
	 * 
	 * @return
	 * returns a byte array containing the 3 lest significant bytes from <b>intToCast</b>.
	 */
	public static byte[] intTo3BytesArray(int intToCast) {
		if (intToCast > 0xFFFFFF || intToCast < 0) {
			throw new InputMismatchException("This int is to big to be cast to only 3 bytes");
		}
		byte [] 
				tempHolder = BigInteger.valueOf(intToCast).toByteArray(),
				arrayToReturn = {0x00, 0x00, 0x00};
		if (tempHolder.length == 4) {
			System.arraycopy(tempHolder, 1, arrayToReturn, 0, 3);
			return arrayToReturn;
		}
		for (int i = 3 - tempHolder.length, baseOffset = i; i < 3; i++) {
			arrayToReturn[i] = tempHolder[i - baseOffset];
		}
		return arrayToReturn;
		
	}

	/**
	 * Cast a <b>int</b> to an array of exactly 4 bytes.
	 * 
	 * @param longToCast
	 * The <b>int</b> to be casted.
	 * 
	 * @return
	 * A array of 4 bytes representing the <b>intToCast</b>;
	 */
	public static byte[] longTo8BytesArray(long longToCast) {
		byte [] 
				tempHolder = BigInteger.valueOf(longToCast).toByteArray(),
				arrayToReturn = new byte[8];
		for (int i = 8 - tempHolder.length, baseOffset = i; i < 8; i++) {
			arrayToReturn[i] = tempHolder[i - baseOffset];
		}
		return arrayToReturn;
	}

	/**
	 * Return the unsigned <b>int</b> value using the 3 <b>byte</b>'s array of
	 * <b>data</b> as the 3 less significant bytes of data to define the value 
	 * to return.
	 * 
	 * @param data
	 * An array of 3 bytes which will be used to create an integer value.
	 * 
	 * @return
	 * An <b>int</b> which represent the 3 byte array passed as parameter.
	 */
	public static int intFrom3bytes(byte[] data) {
		if (data.length != 3) {
			throw new InputMismatchException("The array of data must contain exactly 3 bytes");
		}
		byte [] fourByteArray = new byte[4]; 
		System.arraycopy(data, 0, fourByteArray, 1, 3);
		return ByteBuffer.wrap(fourByteArray).getInt();
	}

}
